//引入express
var express = require('express')
//实例化express
var app = express()
//使用app.use()中间件以及express.static()中间件
app.use(express.static('static'));
//设置处理post请求参数的中间件
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

//返回给客户端的数据
var arr = [
    { "id": 1, "mail": "cbkkhsbf@sina.com", "name": "李丽", "phone": 15844118213, "ingroup": "编辑组", "ismanager": true, "status": true },
    { "id": 2, "mail": "dodghsbf@sina.com", "name": "刘璇", "phone": 16344117755, "ingroup": "美工组", "ismanager": false, "status": true },
    { "id": 3, "mail": "cbdgshrf@sina.com", "name": "张利", "phone": 17444118213, "ingroup": "编辑组", "ismanager": true, "status": false },
    { "id": 4, "mail": "hhdghsbf@sina.com", "name": "吴优", "phone": 15844565613, "ingroup": "审核组", "ismanager": true, "status": false },
    { "id": 5, "mail": "cbshrsbf@sina.com", "name": "李宇", "phone": 15844155667, "ingroup": "美工组", "ismanager": false, "status": true },
    { "id": 6, "mail": "cbdghshr@sina.com", "name": "王丽", "phone": 13258113456, "ingroup": "编辑组", "ismanager": false, "status": true },
    { "id": 7, "mail": "mmdghsbf@sina.com", "name": "周丽", "phone": 13258118213, "ingroup": "编辑组", "ismanager": true, "status": false },
    { "id": 8, "mail": "shrghsbf@sina.com", "name": "孙文文", "phone": 13234568213, "ingroup": "审核组", "ismanager": false, "status": true },
    { "id": 9, "mail": "cbdghsbf@sina.com", "name": "何维", "phone": 13278958213, "ingroup": "编辑组", "ismanager": true, "status": false }
]

//设置接口

//分页
app.get('/user/list', (req, res) => {
    //获取get类型的请求参数：req.query
    var { page, count } = req.query;

    //分页，利用count(每页显示信息条数)，page(页数)来计算需要返回的数据量
    var newarr = arr.slice((page - 1) * count, page * count);
    //将数据返回客户端
    res.send({ code: 200, message: '请求成功！', list: newarr })
})


//模糊搜素
app.get('/user/search', (req, res) => {
    //接收客户端参数
    var { searchkey } = req.query;
    //利用filter方法从用户名的属性里进行过滤，也就是查找是否有符合要求的内容
    var newarr = arr.filter((item) => {
        return new RegExp(searchkey).test(item.name)
    })
    //将符合要求的数据返回给客户端
    res.send({ code: 200, message: '查询成功！', list: newarr })
})


//登陆
app.post('/user/login', (req, res) => {
    var { phone, password } = req.body
    //对客户端的数据进行判断，看是否在已有的用户列表里
    var i = arr.findIndex((item, index) => {
        return item.phone == phone && item.password == password
    })

    if (i != -1) {
        //如果来自客户端的数据符合规则，返回用户信息
        res.send({ code: 200, message: '登陆成功！', userinformation: arr[i], token: '' })
    } else {
        res.send({ code: 400, message: '登陆失败！' })
    }
})

app.listen(6666, () => {
    console.log('服务端运行在:http://localhost:6666');
})